package com.nexgo.payment.trans.download;

import android.support.annotation.NonNull;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.data.json.JsonRecData;
import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.device.pinpad.PinPad;
import com.nexgo.oaf.apiv3.device.pinpad.WorkKeyTypeEnum;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.ManageTransCondition;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsOnlinePresenter;
import com.nexgo.payment.util.ByteUtil;
import com.nexgo.payment.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 终端工作密钥下载
 *
 * @author xhj
 * @time 2018年08月1日
 */
@ManageTransCondition
public class WorkMasterKeyDownPresenter extends AbsOnlinePresenter implements DownloadTransContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(WorkMasterKeyDownPresenter.class.getSimpleName());

    private DownloadTransContract.View mView;

    public WorkMasterKeyDownPresenter(@NonNull DownloadTransContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
        transData.setTransType(TransType.WORK_MASTER_KEY_DOWN);
        return transData;
    }

    @Override
    protected void onFirstAction() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                postMainThread(() -> mView.showOnlineProc(mTransData, null));
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000);//1秒后执行TimeTask的run方法

    }
    public boolean WriteWKey(String pinkey, String pincheck, String mackey, String maccheck, String trankey, String trancheck){
        int sdkResult;
        byte[] ckv;
        PinPad sdkPinPad = ApiDeviceEngine.getInstance().getPinPad();
//        boolean isDes = "0".equals(mRepository.getParamValue(PreferencesConstants.MASTER_KEY_ALGORITHM));
//        boolean isTrackEncrypt = "1".equals(mRepository.getParamValue(PreferencesConstants.TRACK_ENCRYPTED));
        int mKeyIdx = Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.MASTER_KEY_INDEX), "0"));

        mLog.debug("pinkey {},pincheck {}", pinkey, pincheck);
        sdkResult = sdkPinPad.writeWKey(mKeyIdx, WorkKeyTypeEnum.PINKEY, ByteUtils.hexString2ByteArray(pinkey), ByteUtils.hexString2ByteArray(pinkey).length);
        if (sdkResult != SdkResult.Success) {
            postMainThread(() -> mView.setWaitingIndicator(false, null, null));
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.load_tpk_fail)));
            return false;
        }
        ckv = sdkPinPad.calcWKeyKCV(mKeyIdx, WorkKeyTypeEnum.PINKEY);
        mLog.debug("calc ckv {}", ByteUtils.byteArray2HexString(ckv));
        if (!ByteUtil.byteArrayCompare(ByteUtils.hexString2ByteArray(pincheck), ckv,3)) {
            postMainThread(() -> mView.setWaitingIndicator(false, null, null));
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.load_tpk_fail)));
            return false;
        }

        mLog.debug("mackey {},maccheck {}", mackey, maccheck);
        sdkResult = sdkPinPad.writeWKey(mKeyIdx, WorkKeyTypeEnum.MACKEY, ByteUtils.hexString2ByteArray(mackey), ByteUtils.hexString2ByteArray(mackey).length);
        if (sdkResult != SdkResult.Success) {
            postMainThread(() -> mView.setWaitingIndicator(false, null, null));
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.load_tak_fail)));
            return false;
        }
        ckv = sdkPinPad.calcWKeyKCV(mKeyIdx, WorkKeyTypeEnum.MACKEY);
        mLog.debug("calc ckv {}", ByteUtils.byteArray2HexString(ckv));
        if (!ByteUtil.byteArrayCompare(ByteUtils.hexString2ByteArray(maccheck), ckv,3)) {
            postMainThread(() -> mView.setWaitingIndicator(false, null, null));
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.load_tak_fail)));
            return false;
        }
        mLog.debug("value.length {}",ByteUtils.hexString2ByteArray(trankey).length);
        mLog.debug("trankey {},trancheck {}", trankey, trancheck);
        sdkResult = sdkPinPad.writeWKey(mKeyIdx, WorkKeyTypeEnum.TDKEY, ByteUtils.hexString2ByteArray(trankey), ByteUtils.hexString2ByteArray(trankey).length);
        if (sdkResult != SdkResult.Success) {
            postMainThread(() -> mView.setWaitingIndicator(false, null, null));
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.load_tdk_fail)));
            return false;
        }
        ckv = sdkPinPad.calcWKeyKCV(mKeyIdx, WorkKeyTypeEnum.TDKEY);
        mLog.debug("calc ckv {}", ByteUtils.byteArray2HexString(ckv));
        if (!ByteUtil.byteArrayCompare(ByteUtils.hexString2ByteArray(trancheck), ckv, 3)) {
            postMainThread(() -> mView.setWaitingIndicator(false, null, null));
            postMainThread(() -> mView.showError(App.sContext.getString(R.string.load_tdk_fail)));
            return false;
        }
        return true;
    }
    @Override
    protected void onTransSuccess(RecvData recvData) {
        JsonRecData jsonRecData = recvData.getJsonRecData();
        if(null!=jsonRecData.getREQ_BODY()){
            String mackey = jsonRecData.getREQ_BODY().getMackey();
            String maccheck = jsonRecData.getREQ_BODY().getMaccheck();
            String pinkey = jsonRecData.getREQ_BODY().getPinkey();
            String pincheck = jsonRecData.getREQ_BODY().getPincheck();
            String trankey = jsonRecData.getREQ_BODY().getTrankey();
            String trancheck = jsonRecData.getREQ_BODY().getTrancheck();
            boolean writeWKey = WriteWKey(pinkey, pincheck, mackey, maccheck, trankey, trancheck);
            if(writeWKey){
                postMainThread(() -> mView.showTransSuccess());
            }else{
                postMainThread(() -> mView.showTransFailed());
            }
        }

    }
}
